from marshmallow import fields

from webutils.webargs.tornado import use_args
from webutils.tornado.web import RequestHandler
from webutils.tornado.responses import Response
from message_broker import services
from .. import params


class CounterHandler(RequestHandler):
    @use_args(
        {
            'token': params.Token(required=True),
            'key': fields.Str(required=True),
        },
        location='query')
    async def get(self, args, room_id=None):
        counter = services.Counter(
            self.connection,
            room_id=room_id,
            counter_id=args['key'],
        )
        total = await counter.count()
        data = {'total': total}
        resp = Response(errcode=0, errmsg='ok', data=data)
        self.write_response(resp)


class SummaryHandler(RequestHandler):
    @use_args(
        {
            'token': params.Token(required=True),
            'keys': fields.Str(required=False, missing=''),
        },
        location='query')
    async def get(self, args, room_id=None):
        keys = filter(lambda m: m, args['keys'].split(','))
        keys = list(keys) + ['pv']
        data = {}
        for key in keys:
            counter = services.Counter(
                self.connection,
                room_id=room_id,
                counter_id=key,
            )
            count = await counter.count()
            data[key] = count
        chat_service = services.ChatService(self.connection, room_id=room_id)
        data['total_chat'] = await chat_service.get_text_message_count()
        resp = Response(errcode=0, errmsg='ok', data=data)
        self.write_response(resp)
